// 字典管理 Composable
import { ref, computed } from 'vue'
import { getDictionaryByType, getAllDictionaryByType } from '@/api/tenant/dictionary'
import type { Dictionary, DictType } from '@/types/dictionary'

// 字典缓存
const dictionaryCache = new Map<DictType, Dictionary[]>()

/**
 * 使用字典
 * @param type 字典类型
 * @param useCache 是否使用缓存，默认true。在需要实时获取最新数据的场景（如表单）可设为false
 * @param includeDisabled 是否包括已禁用的字典项，默认false。用于显示历史数据
 */
export function useDictionary(type: DictType, useCache = true, includeDisabled = false) {
  const dictionaries = ref<Dictionary[]>([])
  const loading = ref(false)

  // 加载字典
  const loadDictionaries = async () => {
    // 如果启用缓存且缓存中有数据，直接使用
    if (useCache && dictionaryCache.has(type)) {
      dictionaries.value = dictionaryCache.get(type)!
      return
    }

    loading.value = true
    try {
      // 根据 includeDisabled 选择不同的接口
      const response = includeDisabled 
        ? await getAllDictionaryByType(type)
        : await getDictionaryByType(type)
      dictionaries.value = response.data as any || []
      // 如果启用缓存，则缓存结果
      if (useCache) {
        dictionaryCache.set(type, response.data as any || [])
      }
    } catch (error) {
      console.error(`加载字典失败: ${type}`, error)
    } finally {
      loading.value = false
    }
  }

  // 根据代码获取标签
  const getLabel = (code: string) => {
    const dict = dictionaries.value.find((d) => d.dictCode === code)
    return dict?.dictLabel || code
  }

  // 获取所有选项（用于下拉框）
  const options = computed(() => {
    return dictionaries.value.map((d) => ({
      label: d.dictLabel,
      value: d.dictCode,
      remark: d.remark,
    }))
  })

  return {
    dictionaries,
    loading,
    loadDictionaries,
    getLabel,
    options,
  }
}

/**
 * 清除字典缓存
 */
export function clearDictionaryCache(type?: DictType) {
  if (type) {
    dictionaryCache.delete(type)
  } else {
    dictionaryCache.clear()
  }
}

